<!-- 用户列表 -->
<template>
  <div class="container">
    <!-- 搜索框和添加按钮一行 -->
    <div class="search-container">
      <el-input v-model="search" size="small" placeholder="请输入用户名搜索" style="width: 200px" clearable>
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>

      <!-- 添加新用户按钮 -->
      <el-button type="primary" @click="showAddUserDialog" style="margin-left: 16px">
        添加新用户
      </el-button>
    </div>

    <!-- 表格部分保持不变 -->
    <el-scrollbar>
      <el-table :data="filterTableData" style="width: 100%" @row-click="handleRowClick" height="700">
        <el-table-column prop="userId" label="用户ID" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.userId }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" style="color: black" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="ellipsis">
              <el-input v-if="row.isEdit && row.isDelete === '0'" v-model="row.username" size="small" />
              <span v-else>{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="password" label="密码" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input v-if="row.isEdit && row.isDelete === '0'" v-model="row.password" size="small" />
            <span v-else>{{ row.password }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input v-if="row.isEdit && row.isDelete === '0'" v-model="row.phone" size="small"></el-input>
            <span v-else>{{ row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="avatar" label="头像">
          <template #default="{ row }">
            <div v-if="row.isEdit && row.isDelete === '0'" class="avatar-uploader">
              <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false"
                :on-change="(file) => handleAvatarChange(file.raw, row)">
                <el-avatar v-if="row.avatar" :size="60" :src="row.avatarFile
                    ? row.avatar
                    : 'http://localhost:8081' + row.avatar
                  " @error="() => true">
                  <el-icon>
                    <UserFilled />
                  </el-icon>
                </el-avatar>
                <el-avatar v-else :size="60">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-avatar>
              </el-upload>
            </div>
            <el-avatar v-else :size="60" :src="row.avatar ? 'http://localhost:8081' + row.avatar : ''"
              @error="() => true">
              <el-icon>
                <UserFilled />
              </el-icon>
            </el-avatar>
          </template>
        </el-table-column>

        <el-table-column prop="gender" label="性别">
          <template #default="{ row }">
            <el-select v-if="row.isEdit && row.isDelete === '0'" v-model="row.gender" size="small">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
            <span>{{ row.gender === "男" ? "男" : "女" }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="userType" label="用户类型">
          <template #default="{ row }">
            <span>{{ row.userType }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isDelete" label="是否启用">
          <template #default="{ row }">
            <el-select v-if="row.isEdit" v-model="row.isDelete" size="small">
              <el-option label="启用" value="0"></el-option>
              <el-option label="不启用" value="1"></el-option>
            </el-select>
            <span v-else>{{ row.isDelete === "0" ? "启用" : "不启用" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button v-if="!row.isEdit" type="primary" @click="updateRow(row)">
              修改
            </el-button>
            <el-button v-else type="success" @click="saveRow(row)">
              保存
            </el-button>
            <el-button v-if="row.isEdit" @click="cancelEdit(row)">取消</el-button>
            <el-button v-if="!row.isEdit" type="danger" @click="deleteRow(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>

    <!-- 添加用户对话框组件 -->
    <AddUser ref="addUserRef"></AddUser>

    <!-- 添加分页组件 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[8, 16, 32, 64]"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next" class="pagination" />
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from "vue";
import axios from "axios";
import { Search, Plus, UserFilled } from "@element-plus/icons-vue";
import AddUser from "./AddUser.vue";
import { ElMessage, ElMessageBox } from "element-plus";

const users = ref([]);
const originalUsers = ref([]);

const updateRow = (row) => {
  row.isEdit = true;
};

const cancelEdit = (row) => {
  const index = users.value.findIndex((user) => user.userId === row.userId);
  if (index !== -1) {
    if (row.isNew) {
      users.value.splice(index, 1);
    } else {
      // 从原始数据中找到对应的行
      const originalRow = originalUsers.value.find(
        (user) => user.userId === row.userId
      );
      if (originalRow) {
        users.value[index] = { ...originalRow, isEdit: false };
      }
    }
  }
};
const deleteRow = async (row) => {
  try {
    // 添加确认对话框
    await ElMessageBox.confirm("确定要删除这个用户吗？此操作不可恢复", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await axios.post("/deleteUser", row.userId, {
      headers: {
        "Content-Type": "application/json",
        Authorization: sessionStorage.getItem("Authorization"),
      },
    });

    if (response.data.status === 200) {
      ElMessage.success("删除成功");
      users.value = users.value.filter((user) => user.userId !== row.userId);
    } else {
      ElMessage.error(response.data.message || "删除失败");
    }
  } catch (error) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      ElMessage.error("删除失败");
      console.error(error);
    }
  }
};

const saveRow = async (row) => {
  try {
    // 添加管理员判断逻辑
    if (row.userType === "管理员" && row.isDelete === "1") {
      ElMessage.error("不能禁用管理员账号");
      return;
    }

    // 如果有新的头像文件待上传
    if (row.avatarFile) {
      const formData = new FormData();
      formData.append("file", row.avatarFile);

      // 先上传头像
      const uploadResponse = await axios.post(
        `/uploadFile/${row.userId}`,
        formData,
        {
          headers: {
            ...headers,
            "Content-Type": "multipart/form-data",
          },
        }
      );

      if (uploadResponse.data.status === 200) {
        row.avatar = "/res/images/" + uploadResponse.data.data;
      }
    }

    // 保存用户信息
    const response = await axios.post(
      "/updateUser",
      {
        userId: row.userId,
        username: row.username,
        password: row.password,
        phone: row.phone,
        avatar: row.avatar,
        gender: row.gender,
        userType: row.userType,
        isDelete: row.isDelete,
      },
      {
        headers: {
          Authorization: sessionStorage.getItem("Authorization"),
        },
      }
    );

    if (response.data.status === 200 || response.data.status === 500) {
      ElMessage.success("保存成功");
      row.isEdit = false;
      row.avatarFile = null; // 清除临时文件
    } else {
      ElMessage.error("保存失败");
    }
  } catch (error) {
    ElMessage.error("保存失败");
  }
};

const currentPage = ref(1);
const pageSize = ref(8);
const total = ref(0);

// 获取用户列表的方法修改为：
const fetchUsers = async () => {
  try {
    const response = await axios.get("/userList", {
      params: {
        current: currentPage.value,
        size: pageSize.value,
      },
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      },
    });
    const userData = response.data.data.records.map((user) => ({
      ...user,
      isEdit: false,
    }));
    users.value = userData;
    // 保存一份原始数据的深拷贝
    originalUsers.value = JSON.parse(JSON.stringify(userData));
    total.value = response.data.data.total;
  } catch (error) {
    ElMessage.error("获取用户列表失败");
  }
};

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchUsers();
};

// 处理每页显示数量改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchUsers();
};

// 在组件挂载时获取数据
onMounted(() => {
  fetchUsers();
});

const search = ref(""); // 响应式搜索变量
// 计算属性，根据搜索值过滤用户列表
const filterTableData = computed(() =>
  users.value.filter(
    (user) =>
      !search.value ||
      user.username.toLowerCase().includes(search.value.toLowerCase())
  )
);

// 添加对话框相关方法
const addUserRef = ref(null);
const showAddUserDialog = () => {
  addUserRef.value.dialogVisible = true;
};

// 设置请求头
const headers = {
  Authorization: sessionStorage.getItem("Authorization"),
};

// 上传前的验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 6;

  if (!isImage) {
    ElMessage.error("上传头像图片只能是图片格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不超过 6MB!");
    return false;
  }
  return true;
};

// 修改头像选择处理函数
const handleAvatarChange = (file, row) => {
  if (beforeAvatarUpload(file)) {
    // 将文件暂存在行数据中
    row.avatarFile = file;
    // 创建本地预览URL
    row.avatar = URL.createObjectURL(file);
  }
};
</script>
<style scoped>
.pagination {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
}

.container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.search-container {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  /* 使搜索框和按钮垂直居中对齐 */
}

/* 样式根据需要进行调整 */
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

:deep(.el-avatar) {
  background-color: #f0f2f5;
  color: #909399;

  &:hover {
    background-color: #e6e8eb;
  }
}

:deep(.el-icon) {
  font-size: 20px;
}
</style>